package com.sqfw.project.wp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqfw.common.utils.DateUtils;
import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysDictData;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.wp.domain.WpHandleLog;
import com.sqfw.project.wp.domain.WpInfo;
import com.sqfw.project.wp.domain.WpOrganizerBack;
import com.sqfw.project.wp.mapper.WpHandleLogMapper;
import com.sqfw.project.wp.mapper.WpInfoMapper;
import com.sqfw.project.wp.mapper.WpOrganizerBackMapper;
import com.sqfw.project.wp.service.WpAssistUnitService;
import com.sqfw.project.wpReport.domain.WpHoliday;
import com.sqfw.project.wpReport.mapper.WpHolidayMapper;
import com.sqfw.project.wpReport.service.IWpInfoDeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 承办单位 ServiceImpl
 *
 * @author tangxt
 * @date 2025-07-09
 * */
@Slf4j
@Service
public class WpAssistUnitServiceImpl implements WpAssistUnitService {

    @Autowired
    private WpInfoMapper wpInfoMapper;

    @Autowired
    private WpHandleLogMapper wpHandleLogMapper;

    @Autowired
    private WpHolidayMapper wpHolidayMapper;

    @Autowired
    private WpOrganizerBackMapper wpOrganizerBackMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private IWpInfoDeptService wpInfoDeptService;



    // 一天
    private static final long ONE_DAYS = 24 * 60 * 60 * 1000;
    // 三天
    private static final long THREE_DAYS = 3 * 24 * 60 * 60 * 1000;
    // 四天
    private static final long FOUR_DAYS = 4 * 24 * 60 * 60 * 1000;

    private static final Integer dayFive = 5;

    private static final Integer dayTen = 10;

    /**
     * 判断承办单位是否可以退单
     * @param wpInfo 有工单编号，当前状态，承办单位id
     * @return
     * */
    @Override
    public AjaxResult isOrganizerBack(WpInfo wpInfo) {
        WpInfo queryWpInfo = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        if (queryWpInfo == null) {
            return AjaxResult.error("该工单id不存在！");
        }
        if (!queryWpInfo.getNextState().equals(wpInfo.getNextState())) {
            return AjaxResult.error("该工单状态不是承办单位处理,不允许退单！");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!String.valueOf(user.getDeptId()).equals(queryWpInfo.getDeptLevel2())) {
            return AjaxResult.error("该工单的主办单位和您不一致,不允许退单！");
        }
        /** 判断该承办单位是否有退单过 */
        LambdaQueryWrapper<WpOrganizerBack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WpOrganizerBack::getWpid, queryWpInfo.getWpid())
                    .eq(WpOrganizerBack::getDeptLevel2, queryWpInfo.getDeptLevel2());
        WpOrganizerBack wpOrganizerBack = wpOrganizerBackMapper.selectOne(queryWrapper);
        if (wpOrganizerBack != null) {
            if (wpOrganizerBack.getIsOrganizerBack() != null && 1 == wpOrganizerBack.getIsOrganizerBack()) {
                return AjaxResult.error("该承办单位已经退单了一次,不允许再退单了！");
            }
        }
        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setWpid(queryWpInfo.getWpid());
        wpHandleLog.setNextState(queryWpInfo.getNextState());
        wpHandleLog.setNextDepartment1(queryWpInfo.getDeptLevel2());
        List<WpHandleLog> wpHandleLogList =  wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);
        if (CollectionUtils.isEmpty(wpHandleLogList)) {
            return AjaxResult.error("该工单没有到承办单位处理轨迹！");
        }
        // 取第一次派单时间---2025-09-12修改
        // 判断时间，3天内允许退单，3天~4天需要解锁，超过4天不允许退单
        WpHandleLog queryWpHandleLog = wpHandleLogList.get(wpHandleLogList.size() -1);
        Date startDate = queryWpHandleLog.getUpdateTime();
        Date endDate = new Date();
        // 第一步判断， 今天到流转时间，是否超过三天, 没有超过3天，允许退单
        if (endDate.getTime() - startDate.getTime() <= THREE_DAYS) {
            return AjaxResult.success("允许退单！");
        }else {
            long endTime = this.getWeekdayTime(startDate, endDate);
            long remainingTime = endTime - startDate.getTime();
            if (remainingTime <= THREE_DAYS) {
                return AjaxResult.success("允许退单！");
            }else if (remainingTime <=  FOUR_DAYS) {
                if (wpOrganizerBack != null) {
                    // 1--已解锁， 获取解锁时间，只能在一个工作日内退单
                    if (1 == wpOrganizerBack.getIsUntieLock()) {
                        Date untieLockTime = wpOrganizerBack.getUntieLockTime();
                        long currentTime = this.getWeekdayTime(untieLockTime, endDate);
                        long untieRemainingTime = currentTime - untieLockTime.getTime();
                        if (untieRemainingTime <= ONE_DAYS) {
                            return AjaxResult.success("允许退单！");
                        }else {
                            return AjaxResult.error("您没有在解锁后一个工作日退单,不允许退单了！");
                        }
                    }else {
                        return AjaxResult.error("超过三个工作日禁用,需要解锁！");
                    }
                }else {
                    return AjaxResult.error("超过三个工作日禁用,需要解锁！");
                }
            }else {
                return AjaxResult.error("超过四个工作日禁用！");
            }
        }
    }

    /**
     * 承办单位退单
     * @param wpInfo
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult organizerBackWpInfo(WpInfo wpInfo) {
        WpInfo queryWpInfo = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        if (queryWpInfo == null) {
            return AjaxResult.error("该工单id不存在！");
        }
        if (!"承办单位处理".equals(queryWpInfo.getNextState())) {
            return AjaxResult.error("该工单状态不是承办单位处理,不允许退单！");
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!String.valueOf(user.getDeptId()).equals(queryWpInfo.getDeptLevel2())) {
            return AjaxResult.error("该工单的承办单位和您不一致,不允许退单！");
        }
        /** 判断该承办单位是否有退单过 */
        LambdaQueryWrapper<WpOrganizerBack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WpOrganizerBack::getWpid, queryWpInfo.getWpid())
                .eq(WpOrganizerBack::getDeptLevel2, queryWpInfo.getDeptLevel2());
        WpOrganizerBack wpOrganizerBack = wpOrganizerBackMapper.selectOne(queryWrapper);
        if (wpOrganizerBack != null) {
            if (wpOrganizerBack.getIsOrganizerBack() != null && 1 == wpOrganizerBack.getIsOrganizerBack()) {
                return AjaxResult.error("该承办单位已经退单了一次,不允许再退单了！");
            }
        }

        WpOrganizerBack addOrUpdateBack = new WpOrganizerBack();
        addOrUpdateBack.setBackCurrentState(queryWpInfo.getNextState());
        addOrUpdateBack.setIsOrganizerBack(1);
        addOrUpdateBack.setBackReason(wpInfo.getLastmessage());
        addOrUpdateBack.setBackTime(new Date());
        addOrUpdateBack.setBackUserCode(user.getCode());
        addOrUpdateBack.setBackDeptId(user.getDeptId());
        /** 退单数据 */
        if (wpOrganizerBack != null) { // 修改
            addOrUpdateBack.setId(wpOrganizerBack.getId());
            addOrUpdateBack.setUpdateTime(new Date());
            wpOrganizerBackMapper.updateById(addOrUpdateBack);
        }else { // 添加
            addOrUpdateBack.setWpid(queryWpInfo.getWpid());
            addOrUpdateBack.setDeptLevel2(queryWpInfo.getDeptLevel2());
            addOrUpdateBack.setCreateTime(new Date());
            wpOrganizerBackMapper.insert(addOrUpdateBack);
        }
        /** 修改工单--工单回访 */
        WpInfo updatewpInfo = new WpInfo();
        updatewpInfo.setScid(queryWpInfo.getScid());
        updatewpInfo.setLastmessage(wpInfo.getLastmessage());
        updatewpInfo.setState(wpInfo.getState());
        updatewpInfo.setNextState(wpInfo.getNextState());
        updatewpInfo.setUpdatetime(new Date());
        updatewpInfo.setIsOrganizerBack(1);
        updatewpInfo.setReadFlag("0");
        updatewpInfo.setCbdwComplete("1");
        wpInfoMapper.updateCbclWpInfo(updatewpInfo);

//        /** 需要将在主轨迹表添加轨迹数据*/
//        WpHandleLog wpHandleLog = new WpHandleLog();
//        wpHandleLog.setUpdateTime(new Date());
//        wpHandleLog.setWpid(queryWpInfo.getWpid());
//        wpHandleLog.setOperator(user.getCode());
//        wpHandleLog.setMessage(wpInfo.getLastmessage());
//        wpHandleLog.setLastState(wpInfo.getState());
//        wpHandleLog.setNextState(wpInfo.getNextState());
//        wpHandleLog.setSummary(queryWpInfo.getSummary());
//        //部门id
//        wpHandleLog.setDepartment(String.valueOf(user.getDeptId()));
//        String processId = wpHandleLogMapper.getWpHandleLogId();
//        wpHandleLog.setProcessId("SQ" + processId);
//        wpHandleLogMapper.insertWpHandleLog(wpHandleLog);
        /** 需要将在主轨迹表添加轨迹数据*/
        wpInfo.setWpid(queryWpInfo.getWpid());
        this.insertWpHandleLog(wpInfo);
        return AjaxResult.success("退单成功");
    }

    /**
     * 判断工单管理页面是否允许解锁，承办单位超过3天到4天才能解锁
     * @param wpInfo
     * @return
     * */
    @Override
    public AjaxResult isUntieOrganizerLock(WpInfo wpInfo) {
        WpInfo queryWpInfo = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        if (queryWpInfo == null) {
            return AjaxResult.error("该工单id不存在！");
        }
        if (!queryWpInfo.getNextState().equals(wpInfo.getNextState())) {
            return AjaxResult.error("该工单状态不是承办单位处理,不允许解锁！");
        }
        /** 判断是否有解锁---判断该承办单位是否有退单过 */
        LambdaQueryWrapper<WpOrganizerBack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WpOrganizerBack::getWpid, queryWpInfo.getWpid())
                .eq(WpOrganizerBack::getDeptLevel2, queryWpInfo.getDeptLevel2());
        WpOrganizerBack wpOrganizerBack = wpOrganizerBackMapper.selectOne(queryWrapper);
        if (wpOrganizerBack != null) {
            if (wpOrganizerBack.getIsOrganizerBack() != null && 1 == wpOrganizerBack.getIsOrganizerBack()) {
                return AjaxResult.error("该工单在该承办单位已经退单过一次了,不允许解锁！");
            }
            if (wpOrganizerBack.getIsUntieLock() != null && 1 == wpOrganizerBack.getIsUntieLock()) {
                return AjaxResult.error("该工单在该承办单位解锁过一次,不允许解锁！");
            }
        }
        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setWpid(queryWpInfo.getWpid());
        wpHandleLog.setNextState(queryWpInfo.getNextState());
        wpHandleLog.setNextDepartment1(queryWpInfo.getDeptLevel2());
        List<WpHandleLog> wpHandleLogList =  wpHandleLogMapper.selectWpHandleLogList(wpHandleLog);
        if (CollectionUtils.isEmpty(wpHandleLogList)) {
            return AjaxResult.error("该工单没有到承办单位处理轨迹！");
        }
        // 取第一次派单时间---2025-09-12修改
        // 判断时间，3天内不允许解锁，3天~4天才可以解锁，超过4天不允许解锁；
        WpHandleLog queryWpHandleLog = wpHandleLogList.get(wpHandleLogList.size() -1);
        Date startDate = queryWpHandleLog.getUpdateTime();
        Date endDate = new Date();
        // 第一步判断， 今天到流转时间，是否超过三天, 没有超过3天，允许退单
        if (endDate.getTime() - startDate.getTime() <= THREE_DAYS) {
            return AjaxResult.error("该工单没有超过3天，不需要解锁！");
        }else {
            long endTime = this.getWeekdayTime(startDate, endDate);
            long remainingTime = endTime - startDate.getTime();
            // 小于3天
            if (remainingTime <= THREE_DAYS) {
                return AjaxResult.error("该工单没有超过3天，不需要解锁！！");
            }else if (remainingTime <=  FOUR_DAYS) { // 3天到4天
                return AjaxResult.success("允许解锁！");
            }else { // 超过4天
                return AjaxResult.error("该工单超过4天，不能解锁了！");
            }
        }
    }

    /**
     * 工单管理--工单解锁(解锁后，承办单位才能退单)
     * @param wpInfo
     * @return
     *  */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult untieOrganizerLock(WpInfo wpInfo) {
        WpInfo queryWpInfo = wpInfoMapper.selectWpInfoByScid(wpInfo.getScid());
        if (queryWpInfo == null) {
            return AjaxResult.error("该工单id不存在！");
        }
        if (!queryWpInfo.getNextState().equals(wpInfo.getNextState())) {
            return AjaxResult.error("该工单状态不是承办单位处理,不允许解锁！");
        }
        /** 判断是否有解锁---判断该承办单位是否有退单过 */
        LambdaQueryWrapper<WpOrganizerBack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WpOrganizerBack::getWpid, queryWpInfo.getWpid())
                .eq(WpOrganizerBack::getDeptLevel2, queryWpInfo.getDeptLevel2());
        WpOrganizerBack wpOrganizerBack = wpOrganizerBackMapper.selectOne(queryWrapper);
        if (wpOrganizerBack != null) {
            if (wpOrganizerBack.getIsOrganizerBack() != null && 1 == wpOrganizerBack.getIsOrganizerBack()) {
                return AjaxResult.error("该工单在该承办单位已经退单过一次了,不允许解锁！");
            }
            if (wpOrganizerBack.getIsUntieLock() != null && 1 == wpOrganizerBack.getIsUntieLock()) {
                return AjaxResult.error("该工单在该承办单位解锁过一次,不允许解锁！");
            }
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WpOrganizerBack addWpOrganizerBack = new WpOrganizerBack();
        addWpOrganizerBack.setWpid(queryWpInfo.getWpid());
        addWpOrganizerBack.setDeptLevel2(queryWpInfo.getDeptLevel2());
        addWpOrganizerBack.setIsUntieLock(1);
        addWpOrganizerBack.setUntieLockTime(new Date());
        addWpOrganizerBack.setUntieCode(user.getCode());
        addWpOrganizerBack.setUntieDeptId(user.getDeptId());
        addWpOrganizerBack.setUntieCurrentState(queryWpInfo.getNextState());
        addWpOrganizerBack.setCreateTime(new Date());
        wpOrganizerBackMapper.insert(addWpOrganizerBack);

        /** 需要将在主轨迹表添加轨迹数据*/
        WpHandleLog wpHandleLog = new WpHandleLog();
        wpHandleLog.setUpdateTime(new Date());
        wpHandleLog.setWpid(queryWpInfo.getWpid());
        wpHandleLog.setOperator(user.getCode());
        wpHandleLog.setMessage("解锁");
        wpHandleLog.setLastState("工单管理-解锁");
        wpHandleLog.setNextState("解锁后-承办单位处理");
        wpHandleLog.setSummary(queryWpInfo.getSummary());
        //部门id
        wpHandleLog.setDepartment(String.valueOf(user.getDeptId()));
        String processId = wpHandleLogMapper.getWpHandleLogId();
        wpHandleLog.setProcessId("SQ" + processId);
        wpHandleLogMapper.insertWpHandleLog(wpHandleLog);

        return AjaxResult.success("解锁成功！");
    }

    /**
     * 查询承办单位退单的记录,和工单管理解锁记录
     * @param wpOrganizerBack
     * @param page
     * @return
     * */
    @Override
    public Page<WpOrganizerBack> pageWpOrganizerBack(Page page, WpOrganizerBack wpOrganizerBack) {
        LambdaQueryWrapper<WpOrganizerBack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(wpOrganizerBack.getDeptLevel2()), WpOrganizerBack::getDeptLevel2, wpOrganizerBack.getDeptLevel2())
                .like(StringUtils.isNotBlank(wpOrganizerBack.getWpid()), WpOrganizerBack::getWpid, wpOrganizerBack.getWpid())
                .eq(wpOrganizerBack.getIsOrganizerBack() != null, WpOrganizerBack::getIsOrganizerBack, wpOrganizerBack.getIsOrganizerBack())
                .eq(wpOrganizerBack.getIsUntieLock() != null, WpOrganizerBack::getIsUntieLock, wpOrganizerBack.getIsUntieLock());
        // 创建时间范围
        queryWrapper.ge(wpOrganizerBack.getStartCreateTime() != null, WpOrganizerBack::getCreateTime, wpOrganizerBack.getStartCreateTime())
                .le(wpOrganizerBack.getEndCreateTime() != null, WpOrganizerBack::getCreateTime, wpOrganizerBack.getEndCreateTime());
        // 排序
        queryWrapper.orderByDesc(WpOrganizerBack::getCreateTime);
        Page<WpOrganizerBack> backPage = wpOrganizerBackMapper.selectPage(page, queryWrapper);
        if (!CollectionUtils.isEmpty(backPage.getRecords())) {
            Set<Long> deptIds = new HashSet<>();
            for (WpOrganizerBack organizerBack :  backPage.getRecords()) {
                if (StringUtils.isNotBlank(organizerBack.getDeptLevel2())) {
                    deptIds.add(Long.parseLong(organizerBack.getDeptLevel2()));
                }
            }
            if (!CollectionUtils.isEmpty(deptIds)) {
                List<SysDept> deptList = sysDeptMapper.getSysDeptByDeptIds(deptIds);
                if (!CollectionUtils.isEmpty(deptList)) {
                    backPage.getRecords().stream().forEach(b -> {
                        if (StringUtils.isNotBlank(b.getDeptLevel2())) {
                            for (SysDept sysDept : deptList) {
                                if (b.getDeptLevel2().equals(String.valueOf(sysDept.getDeptId()))) {
                                    b.setDeptLevel2Name(sysDept.getDeptName());
                                    break;
                                }
                            }
                        }
                    });
                }
            }
        }
        return backPage;
    }

    /**
     * 获取承办单位退单的时间，减掉节假日
     * @param startDate 流转时间
     * @param endDate 当前时间
     * */
    public long getWeekdayTime(Date startDate, Date endDate) {
        Map<String, String> map = new HashMap<>();
        map.put("startDtime", DateUtils.dateTime(startDate));
        map.put("endDtime", DateUtils.dateTime(endDate));
        // 节假日
        List<WpHoliday> wpHolidayList = wpHolidayMapper.selectWpHolidayByDtime(map);
        boolean isStartDate = false;
        boolean isEndDate = false;
        String startDateStr = DateUtils.dateTime(startDate);
        String endDateStr = DateUtils.dateTime(endDate);
        // 这段时间没有节假日
        if (CollectionUtils.isEmpty(wpHolidayList)) {
            return endDate.getTime();
        }else {
            for (WpHoliday wpHoliday : wpHolidayList) {
                // 流转时间
                if (startDateStr.equals(DateUtils.dateTime(wpHoliday.getDtime()))) {
                    isStartDate = true;
                }
                // 判断今天时间
                if (endDateStr.equals(DateUtils.dateTime(wpHoliday.getDtime()))) {
                    isEndDate = true;
                }
            }
        }
        // 1.流转时间和判断的今天都是节假日
        if (isStartDate && isEndDate) {
            Date nowDate = endDate;
            int day = wpHolidayList.size() -2;
            if (day > 0) {
                nowDate = DateUtils.plusDay(endDate, -day);
            }
            long startTime = DateUtils.plusDay(DateUtils.parseDate(startDateStr), 1).getTime() - startDate.getTime();
            long endTime = endDate.getTime() - DateUtils.parseDate(endDateStr).getTime(); ;
            return nowDate.getTime() - (startTime + endTime);
        }else if (isStartDate) { // 2.流转时间是节假日
            Date nowDate = endDate;
            int day = wpHolidayList.size() -1;
            if (day > 0) {
                nowDate = DateUtils.plusDay(endDate, -day);
            }
            long startTime = DateUtils.plusDay(DateUtils.parseDate(startDateStr), 1).getTime() - startDate.getTime();
            return nowDate.getTime() - startTime;
        }else if (isEndDate) { // 3.判断的今天是节假日
            Date nowDate = endDate;
            int day = wpHolidayList.size() -1;
            if (day > 0) {
                nowDate = DateUtils.plusDay(endDate, -day);
            }
            long endTime = endDate.getTime() - DateUtils.parseDate(endDateStr).getTime(); ;
            return nowDate.getTime() - endTime;
        }else { // 4.流转时间和判断的今天都不是节假日
            int day = wpHolidayList.size();
            return DateUtils.plusDay(endDate, -day).getTime();
        }
    }


    //新增轨迹表数据
    @Transactional
    public void insertWpHandleLog(WpInfo wpInfo) {
        Date date = new Date();
        //添加完成后，需要将在主轨迹表添加轨迹数据
        WpHandleLog wpHandleLog = new WpHandleLog();
        //登录人员信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        wpHandleLog.setWpid(wpInfo.getWpid());
        wpHandleLog.setOperator(user.getCode());
        wpHandleLog.setMessage(wpInfo.getLastmessage());
        wpHandleLog.setLastState(wpInfo.getState());
        wpHandleLog.setNextState(wpInfo.getNextState());
        wpHandleLog.setSummary(wpInfo.getSummary());
        //部门id
        wpHandleLog.setDepartment(user.getDeptId().toString());

        //特有字段（承办单位处理,工单回访）
        wpHandleLog.setSatisfied(wpInfo.getSatisfied());
        wpHandleLog.setReasonable(wpInfo.getReasonable());
        wpHandleLog.setSolved(wpInfo.getSolved());
        wpHandleLog.setBackClass(wpInfo.getBackClass());
        wpHandleLog.setUpdateTime(date);
        if ("督导处理".equals(wpHandleLog.getNextState()) || "承办单位处理".equals(wpHandleLog.getNextState())) {
            //主办部门id
            wpHandleLog.setNextDepartment1(wpInfo.getDeptLevel2());
            //协助部门id
            wpHandleLog.setDeptLevel2vice1(wpInfo.getDeptLevel2vice1());
            wpHandleLog.setDeptLevel2vice2(wpInfo.getDeptLevel2vice2());
        }
        //代表承办单位到回访操作
        if ("工单回访".equals(wpHandleLog.getNextState()) && (!"质检审核处理".equals(wpHandleLog.getLastState()))) {
            //工单回访，需要向hfState中插入数据（1:5天内完成，2:10天内完成，3：超时完成）
            WpHandleLog log = new WpHandleLog();
            log.setWpid(wpInfo.getWpid());
            log.setNextState("承办单位处理");
            List<WpHandleLog> handleLogList = wpHandleLogMapper.selectWpHandleLogList(log);
            if (!CollectionUtils.isEmpty(handleLogList)) {
                // 取最新一次
                WpHandleLog logCon = handleLogList.stream()
                        .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                        .orElse(null);
                // 取第一次派单时间---2025-09-12修改
                WpHandleLog logMin = handleLogList.stream()
                        .min(Comparator.comparing(WpHandleLog::getUpdateTime))
                        .orElse(null);
                if (logCon != null && logMin != null) {
                    //这一块是判断工作日相关
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    long year = calendar.get(Calendar.YEAR);
                    WpHoliday wpHoliday = new WpHoliday();
                    wpHoliday.setYearid(year);
                    List<WpHoliday> wpHolidays = wpHolidayMapper.selectWpHolidayList(wpHoliday);
                    List<String> dates = wpHolidays.stream()
                            .map(WpHoliday::getDtime)
                            .map(simpleDateFormat::format)
                            .collect(Collectors.toList());
                    Date timeFive = wpInfoDeptService.checkOntime(logMin.getUpdateTime(), dayFive, dates);

                    if (date.compareTo(timeFive) <= 0) {
                        //代表5天内完成
                        logCon.setHfState("1");
                    } else {
                        Date timeTen = wpInfoDeptService.checkOntime(logMin.getUpdateTime(), dayTen, dates);
                        try {
                            if (date.compareTo(timeTen) <= 0) {
                                //代表10天内完成
                                logCon.setHfState("2");
                            } else {
                                //代表超时完成
                                logCon.setHfState("3");
                            }
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if (com.sqfw.common.utils.StringUtils.isNotEmpty(wpInfo.getTimeBoundry())){
                                Date parse = dateFormat.parse(wpInfo.getTimeBoundry());
                                //如果是延期，且五天内没有完成
                                if (date.compareTo(parse)<=0){
                                    //代表10天内完成
                                    logCon.setHfState("2");
                                }
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                    //todo 增加更新之前所有的轨迹
                    //更新之前所有历史轨迹的HfState字段值，避免在统计报表中统计条件hf_state为null的数据出现偏差不一致
                    if(com.sqfw.common.utils.StringUtils.isNotEmpty(logCon.getHfState())){
                        wpHandleLogMapper.updateAllHistoryHfSate(logCon);
                    }
                    wpHandleLogMapper.updateWpHandleLog(logCon);
                }
            }
        }
        String processId = wpHandleLogMapper.getWpHandleLogId();
        wpHandleLog.setProcessId("SQ" + processId);
        wpHandleLogMapper.insertWpHandleLog(wpHandleLog);
    }


}
